package com.tangtang.rocket.provider;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@EnableEurekaClient
@SpringBootApplication
public class ProviderApplication {
    public static void main(String[] args) throws Exception{
        SpringApplication.run(ProviderApplication.class, args);

        final DefaultMQProducer producer = new DefaultMQProducer("my_provider");

        producer.setNamesrvAddr("rocketmq-server-0:9876");
        producer.start();

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(){
                @Override
                public void run() {
                    while (true){
                        try {
                            Message msg = new Message("TopicTest" /* Topic */,
                                    "TagA" /* Tag */,
                                    ("Hello RocketMQ " +
                                            finalI).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
                            );
                            //Call send message to deliver message to one of brokers.
                            SendResult sendResult = producer.send(msg);
                            System.out.printf("%s%n", sendResult);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        } catch (MQClientException e) {
                            e.printStackTrace();
                        } catch (RemotingException e) {
                            e.printStackTrace();
                        } catch (MQBrokerException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }.start();
        }

        while (true){
            Thread.sleep(1000);
        }
    }
}
